using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using eDirectory.Common.Message;
using eDirectory.Domain.AppServices;

namespace eDirectory.Mvc.Services
{
    public class ResponseManagerAttribute : ActionFilterAttribute
    {
        public override void  OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (Container.RequestContext.ResponseManager.HasWarnings)
            {
                filterContext.HttpContext.Response.AddHeader("Warning", Container.RequestContext.ResponseManager.RetrieveWarningsToString());
                filterContext.Controller.ViewBag.Warnings = Container.RequestContext.ResponseManager.Warnings;
            }
            base.OnActionExecuted(filterContext);
        }
    }
    
    public class MvcResponseManager
        :IResponseManager
    {
        private readonly IList<BusinessWarning> _warningList = new List<BusinessWarning>();
        private BusinessExceptionDto _businessExceptionDto;

        public void CheckResponse(Response response)
        {
            if (response.HasException)
            {
                _businessExceptionDto = response.BusinessException;
            }
            if (response.HasWarning)
            {
                response.BusinessWarnings.ToList().ForEach(w => _warningList.Add(w));
            }
        }

        public bool HasWarnings
        {
            get { return _warningList.Any(); }
        }

        public bool HasException
        {
            get { return _businessExceptionDto != null; }
        }

        public string RetrieveWarningsToString()
        {
            return !HasWarnings 
                       ? string.Empty
                       : string.Join("\n", _warningList.Select(w => w.Message));
        }

        public IEnumerable<string> Warnings
        {
            get { return _warningList.Select(w => w.Message); }
        }

        public BusinessExceptionDto BusinessExceptionDto
        {
            get { return _businessExceptionDto; }
        }
    }
}